<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="10" :lg="11" :md="12" :sm="24">
            <a-form-item :label="$t('订单时间')">
              <a-date-picker
                :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                dateFormat="YYYY-MM-DD HH:mm:ss"
                :placeholder="$t('请选择开始时间')"
                class="query-group-cust"
                v-model="queryParam.createTime_begin"
              ></a-date-picker>
              <span class="query-group-split-cust"></span>
              <a-date-picker
                :show-time="{ defaultValue: moment('23:59:59', 'HH:mm:ss') }"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                dateFormat="YYYY-MM-DD HH:mm:ss"
                :placeholder="$t('请选择结束时间')"
                class="query-group-cust"
                v-model="queryParam.createTime_end"
              ></a-date-picker>
            </a-form-item>
          </a-col>
          <a-col :xl="5" :lg="6" :md="7" :sm="24">
            <a-form-item :label="$t('支付方式')">
              <a-select v-model="queryParam.payType">
                <a-select-option :value="item.name" :key="index" v-for="(item, index) in paytypeList">{{
                  item.nameText
                }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('会员信息')">
                <a-input :placeholder="$t('请输入手机号/卡号/姓名/邮箱')" v-model="queryParam.memberInfo"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('订单状态')">
                <a-select v-model="queryParam.state">
                  <a-select-option :value="item.value" :key="index" v-for="(item, index) in orderstateList">{{
                    item.title
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('业务渠道')">
                <a-select v-model="queryParam.deviceType">
                  <a-select-option :value="item.value" :key="index" v-for="(item, index) in deviceinfoList">{{
                    item.title
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('设备名称(编码)')">
                <a-select show-search :filter-option="false" @search="handleSearch" v-model="queryParam.deviceId">
                  <a-select-option :value="item.id" :key="index" v-for="(item, index) in deviceList">
                    <span>{{ item.name }}</span>
                    <span v-if="item.name != $t('全部')">({{ item.id }})</span>
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('操作员')">
                <a-select v-model="queryParam.createBy">
                  <a-select-option :value="item.id" :key="index" v-for="(item, index) in userList">{{
                    item.realname
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('订单号')">
                <a-input :placeholder="$t('请输入订单号/关联订单号')" v-model="queryParam.orderInfo"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('订单类型')">
                <a-select v-model="queryParam.orderType">
                  <a-select-option value="1,3,5,7,9">{{ $t('全部') }}</a-select-option>
                  <a-select-option value="1">{{ $t('兑换订单') }}</a-select-option>
                  <a-select-option value="3">{{ $t('兑换退单') }}</a-select-option>
                  <a-select-option value="5">{{ $t('抖音套餐') }}</a-select-option>
                  <a-select-option value="7">{{ $t('券核销') }}</a-select-option>
                  <a-select-option value="9">{{ $t('取爆米花') }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24" v-if="!tenantid">
              <a-form-item :label="$t('门店')">
                <a-select v-model="queryParam.shopCode">
                  <a-select-option v-for="(item, i) in shops" :key="i" :value="item.value"
                    >{{ item.title }}<span v-if="item.value != ''">（{{ item.value }}）</span></a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="8" :lg="9" :md="10" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">{{ $t('查询') }}</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">{{
                $t('重置')
              }}</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? $t('收起') : $t('展开') }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
              <a-button
               v-has="'BisOrderController:export'"
                type="primary"
                icon="download"
                :loading="exloading"
                style="margin-left: 8px"
                v-if="toggleSearchStatus"
                @click="handleExportXls($t('商品兑换订单'))"
                >{{ $t('导出') }}</a-button
              >
              <a-popover :title="$t('自定义列')" trigger="click" placement="leftBottom">
                <template slot="content">
                  <a-checkbox-group
                    @change="onColSettingsChange"
                    v-model="settingColumns"
                    :defaultValue="settingColumns"
                  >
                    <a-row style="width: 400px">
                      <template v-for="(item, i) in defColumns">
                        <template v-if="item.key != 'rowIndex' && item.dataIndex != 'action'">
                          <a-col :span="12" :key="i"
                            ><a-checkbox :value="item.dataIndex"
                              ><j-ellipsis :value="item.title" :length="10"></j-ellipsis></a-checkbox
                          ></a-col>
                        </template>
                      </template>
                    </a-row>
                  </a-checkbox-group>
                </template>
                <a-button style="margin-left: 8px" type="setting" v-if="toggleSearchStatus">{{ $t('设置显示项') }}</a-button>
              </a-popover>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- table区域-begin -->
    <div class="scroll-tabox">
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :scroll="{ x: true, y: tableHeight }"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :customHeaderRow="customHeaderRow"
        :customRow="customRow"
        @change="handleTableChange"
      >
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">{{ $t('无图片') }}</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt=""
            style="max-width: 80px; font-size: 12px; font-style: italic"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">{{ $t('无文件') }}</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            {{ $t('下载') }}
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="showModal(record)">{{ $t('详情') }}</a>
        </span>

        <template slot="footer">
          <div style="font-weight: bold">
            <span style="margin-left: 15px; margin-right: 5px">{{ $t('订单金额') }}：</span>
            <span>{{ totalInfo.price ? totalInfo.price.toFixed(2) : '0.00' }}</span>
            <span style="margin-left: 15px; margin-right: 5px">{{ $t('优惠券抵扣') }}：</span>
            <span>{{ totalInfo.discountAmount ? totalInfo.discountAmount.toFixed(2) : '0.00' }}</span>
            <span style="margin-left: 15px; margin-right: 5px">{{ $t('优惠金额') }}：</span>
            <span>{{ totalInfo.activityDiscount ? totalInfo.activityDiscount.toFixed(2) : '0.00' }}</span>
            <span style="margin-left: 15px; margin-right: 5px">{{ $t('实付金额') }}：</span>
            <span>{{ totalInfo.payAmount ? totalInfo.payAmount.toFixed(2) : '0.00' }}</span>
          </div>
        </template>
      </a-table>
    </div>

    <type-name-modal ref="typeNameForm"></type-name-modal>
  </a-card>
</template>

<script>
import Vue from 'vue'
import moment from 'moment'
import '@/assets/less/TableExpand.less'
import { getAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { initDictOptions, filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import TypeNameModal from './modules/TypeNameModal'

export default {
  name: 'ExchangeList',
  mixins: [JeecgListMixin],
  components: {
    TypeNameModal,
  },
  data() {
    return {
      description: '商品兑换订单',
      moment,
      tenantid: Vue.ls.get('TENANT_ID'),
      queryParam: {
        payType: '',
        orderInfo: '',
        state: '2',
        deviceType: '',
        deviceId: '',
        createBy: '',
        orderType: '1,3,5,7,9',
        shopCode: '',
      },
      //列设置
      settingColumns: [],
      // 表头
      columns: [],
      // 表头
      defColumns: [
        {
          title: this.$t('订单号'),
          align: 'center',
          sorter: true,
          dataIndex: 'id',
          width: 170,
        },
        {
          title: this.$t('兑换时间'),
          align: 'center',
          sorter: true,
          dataIndex: 'createTime',
          width: 156,
        },
        {
          title: this.$t('订单类型'),
          align: 'center',
          sorter: true,
          dataIndex: 'orderType_dictText',
          width: 96,
        },
        {
          title: this.$t('会员手机号'),
          align: 'center',
          dataIndex: 'memberPhone',
          width: 100,
        },
        {
          title: this.$t('卡号'),
          align: 'center',
          dataIndex: 'cardSn',
          width: 96,
        },
        {
          title: this.$t('邮箱'),
          align: 'center',
          dataIndex: 'email',
          width: 160,
        },
        {
          title: this.$t('会员姓名'),
          align: 'center',
          dataIndex: 'memberName',
          width: 96,
          customCell: (r, i) => {
            return {
              style: {
                whiteSpace: 'normal',
              },
            }
          },
        },
        {
          title: this.$t('支付方式'),
          align: 'center',
          dataIndex: 'payType_dictText',
          width: 130,
          customCell: (r, i) => {
            return {
              style: {
                whiteSpace: 'normal',
              },
            }
          },
        },
        {
          title: this.$t('订单金额'),
          align: 'center',
          sorter: true,
          dataIndex: 'price',
          customRender: (text, record) => {
            return record.price.toFixed(2)
          },
          width: 96,
          customCell: (r, i) => {
            return {
              style: {
                whiteSpace: 'normal',
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('优惠券抵扣'),
          align: 'center',
          sorter: true,
          dataIndex: 'discountAmount',
          customRender: (text, record) => {
            return record.discountAmount.toFixed(2)
          },
          width: 156,
          customCell: (r, i) => {
            return {
              style: {
                whiteSpace: 'normal',
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('优惠金额'),
          align: 'center',
          sorter: true,
          dataIndex: 'activityDiscount',
          customRender: (text, record) => {
            return record.activityDiscount.toFixed(2)
          },
          width: 150,
          customCell: (r, i) => {
            return {
              style: {
                whiteSpace: 'normal',
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('会员优惠'),
          align: 'center',
          sorter: true,
          dataIndex: 'memberDiscount',
          customRender: (text, record) => {
            return record.memberDiscount.toFixed(2)
          },
          width: 160,
          customCell: (r, i) => {
            return {
              style: {
                whiteSpace: 'normal',
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('实付金额'),
          align: 'center',
          sorter: true,
          dataIndex: 'payAmount',
          customRender: (text, record) => {
            return record.payAmount.toFixed(2)
          },
          width: 96,
          customCell: (r, i) => {
            return {
              style: {
                whiteSpace: 'normal',
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('订单状态'),
          align: 'center',
          sorter: true,
          dataIndex: 'state_dictText',
          width: 96,
          customCell: (r, i) => {
            return {
              style: {
                whiteSpace: 'normal',
              },
            }
          },
        },
        {
          title: this.$t('业务渠道'),
          align: 'center',
          sorter: true,
          dataIndex: 'deviceType_dictText',
          width: 100,
          customCell: (r, i) => {
            return {
              style: {
                whiteSpace: 'normal',
              },
            }
          },
        },
        {
          title: this.$t('设备名称'),
          align: 'center',
          sorter: true,
          dataIndex: 'deviceName',
          width: 124,
          customCell: (r, i) => {
            return {
              style: {
                whiteSpace: 'normal',
              },
            }
          },
        },
        {
          title: this.$t('设备编码'),
          align: 'center',
          sorter: true,
          dataIndex: 'deviceId',
          width: 116,
          customCell: (r, i) => {
            return {
              style: {
                whiteSpace: 'normal',
              },
            }
          },
        },
        {
          title: this.$t('操作员'),
          align: 'center',
          sorter: true,
          dataIndex: 'createBy',
          width: 100,
          customCell: (r, i) => {
            return {
              style: {
                whiteSpace: 'normal',
              },
            }
          },
        },
        {
          title: this.$t('关联订单号'),
          align: 'center',
          dataIndex: 'subOrderId',
          width: 170,
          customCell: () => {
            return {
              style: {
                wordWrap: 'break-word',
                overflowWrap: 'break-word',
                whiteSpace: 'pre-wrap',
              },
            }
          },
        },
        {
          title: this.$t('操作'),
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 80,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/order/bisOrder/list',
        delete: '/order/bisOrder/delete',
        exportXlsUrl: '/order/bisOrder/exportXls',
        totalUrl: '/order/bisOrder/total',
      },
      dictOptions: {
        payType: [],
      },
      paytypeList: [],
      orderstateList: [],
      deviceinfoList: [],
      deviceList: [],
      userList: [],
      shops: [],
      isfooter: true,
      isCustom: true,
      isHideData: false,
      hideCond: 2,
    }
  },
  created() {
    if (!this.tenantid) {
      let dtl = {
          title: this.$t('门店编码'),
          align: 'center',
          dataIndex: 'shopCode',
          sorter: true,
          width: 96,
          customCell: (r, i) => {
            return {
              style: {
                whiteSpace: 'normal',
              },
            }
          },
        },
        dtl1 = {
          title: this.$t('门店名称'),
          align: 'center',
          dataIndex: 'shopCode_dictText',
          sorter: true,
          width: 100,
          customCell: (r, i) => {
            return {
              style: {
                whiteSpace: 'normal',
              },
            }
          },
        }
      this.defColumns.unshift(dtl1)
      this.defColumns.unshift(dtl)
    }
    this.initColumns()
  },
  mounted() {
    let that = this
    document.onkeydown = function (e) {
      let key = window.event.keyCode
      if (key == 75 && event.ctrlKey) {
        window.event.preventDefault()
        that.isHideData = false
        that.queryParam.dataType = 0
        that.searchQuery()
      }
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    initDictConfig() {
      this.customInit()
      let param = {}
      param.pageNo = 1
      param.pageSize = 9999
      param.orderType = 1
      getAction('/pay/bisPayType/list', param).then((res) => {
        if (res.success) {
          let arr = res.result.records.filter((rds) => {
            return (
              rds.state == 'Y' && (rds.name == 6 || rds.name == 7 || rds.name == 10 || rds.name == 11 || rds.name == 12)
            )
          })
          this.paytypeList = arr
          this.paytypeList.unshift({ name: '', nameText: this.$t('全部') })
        }
      })
      initDictOptions('bis_order.state').then((res) => {
        if (res.success) {
          this.orderstateList = res.result
          this.orderstateList.unshift({ value: '', title: this.$t('全部') })
        }
      })
      initDictOptions('bis_device_info.type').then((res) => {
        if (res.success) {
          this.deviceinfoList = res.result
          this.deviceinfoList.unshift({ value: '', title: this.$t('全部') })
        }
      })
      initDictOptions('bis_shop,name,code').then((res) => {
        if (res.success) {
          this.shops = res.result
          this.shops.unshift({ value: '', title: this.$t('全部') })
        }
      })
      getAction('/sys/user/list').then((res) => {
        if (res.success) {
          this.userList = res.result.records
          this.userList.forEach((col) => {
            col.id = col.realname
          })
          this.userList.unshift({ id: '', realname: this.$t('全部') })
        }
      })
    },
    customInit() {
      this.handleSearch('')
      this.isHideData = true
      this.queryParam.dataType = 2
      this.loadData(1)
    },
    handleSearch(value) {
      let query = {}
      if (value) {
        query.deviceInfo = value
      }
      getAction('/device/bisDeviceInfo/list', query).then((res) => {
        if (res.success) {
          this.deviceList = res.result.records
          this.deviceList.unshift({ id: '', name: this.$t('全部') })
        }
      })
    },
    searchReset() {
      this.queryParam = {
        createTime_begin: '',
        createTime_end: '',
        payType: '',
        orderInfo: '',
        state: '2',
        deviceType: '',
        deviceId: '',
        createBy: '',
        orderType: '1,3,5,7,9',
        shopCode: '',
      }
      this.selectedRowIndex = []
      this.customInit()
    },
    //列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ':colsettings'
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
      this.settingColumns = checkedValues
      const cols = this.defColumns.filter((item) => {
        if (item.key == 'rowIndex' || item.dataIndex == 'action') {
          return true
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true
        }
        return false
      })
      this.columns = cols
    },
    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');
      var key = this.$route.name + ':colsettings'
      let colSettings = Vue.ls.get(key)
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = []
        this.defColumns.forEach(function (item, i, array) {
          allSettingColumns.push(item.dataIndex)
        })
        this.settingColumns = allSettingColumns
        this.columns = this.defColumns
      } else {
        this.settingColumns = colSettings
        const cols = this.defColumns.filter((item) => {
          if (item.key == 'rowIndex' || item.dataIndex == 'action') {
            return true
          }
          if (colSettings.includes(item.dataIndex)) {
            return true
          }
          return false
        })
        this.columns = cols
      }
    },
    showModal(record) {
      this.$refs.typeNameForm.edit(record)
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>